package br.edu.ufcg.dsc.actions.loan;

import org.apache.struts2.config.ParentPackage;
import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;
import org.apache.struts2.dispatcher.ServletDispatcherResult;
import org.apache.struts2.dispatcher.ServletRedirectResult;

import br.edu.ufcg.dsc.actions.BaseLoggedAction;
import br.edu.ufcg.dsc.domain.Loan;
import br.edu.ufcg.dsc.domain.Unit;
import br.edu.ufcg.dsc.domain.User;
import br.edu.ufcg.dsc.services.LoanService;
import br.edu.ufcg.dsc.services.UnitService;
import br.edu.ufcg.dsc.services.UserService;

import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validation;

@Results(value = {
@Result(name="success", type=ServletRedirectResult.class, value="/index.action?message=Loan successfully created."),
@Result(name="input", type=ServletDispatcherResult.class, value="/jsp/loan/loanDetails.jsp")})
@Validation
@ParentPackage("myPackage")
public class CreateAction extends BaseLoggedAction {

	private static final long serialVersionUID = 1L;

	private String user, unit;

	private int days;
	
	@Override
	protected String executeIfLogged() {
		User us = UserService.find(user);
		Unit un = UnitService.find(unit);
		
		Loan loan = new Loan(us, un, days);

		us.getLoans().add(loan);
		un.getLoans().add(loan);
		
		LoanService.persist(loan);
		
		return SUCCESS;
	}
	
	@Override
	public void validate() {
		super.validate();
		
		if ("".equals(user) || "".equals(unit))
			return;
		
		if (user != null  && UserService.find(user) == null)
			addFieldError("user", getText("loan.user.invalid"));
		if (unit != null && UnitService.find(unit) == null)
			addFieldError("unit", getText("loan.unit.invalid"));
		if (unit != null && LoanService.findByUnit(unit) != null)
			addFieldError("unit", getText("loan.unit.exists"));
	}
	
	@RequiredStringValidator(key = "loan.user.mandatory", message = "Please enter a user login.", trim = true)
	public String getUser() {
		return user;
	}

	
	public void setUser(String user) {
		this.user = user;
	}

	@RequiredStringValidator(key = "loan.unit.mandatory", message = "Please enter a unit id.", trim = true)
	public String getUnit() {
		return unit;
	}

	public void setUnit(String unit) {
		this.unit = unit;
	}

	@RequiredFieldValidator(key = "loan.days.mandatory", message = "Please enter a quanitty of days.")
	public int getDays() {
		return days;
	}

	public void setDays(int days) {
		this.days = days;
	}
}
